﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Settings;
using Utils;

namespace PanasonicWarranty.Business
{
    public partial class pa_WarrantyPackage
    {
        public static DateTime GetExpriredDate(int Id, DateTime registerDate)
        {
            using (var context = new DBWarrantyDataContext(AppSetting.ConnectionString))
            {
                var endDate = registerDate.AddMonths(context.pa_WarrantyPackages.FirstOrDefault(p => p.WarrantyPackageID == Id).WarrantyPeriod);
                return endDate.GetLastDayOfMonth();
            }
        }

        public static List<pa_WarrantyPackage> Paging(int currentPage, int pageSize, ref int totalRecord,
                                           string code, string name, int? period,
                                           string unit, bool? disabled)
        {
            using (var context = new DBWarrantyDataContext(AppSetting.ConnectionString))
            {
                var resutl = context.pa_WarrantyPackages.AsQueryable();
                if (!string.IsNullOrWhiteSpace(code))
                {
                    resutl = resutl.Where(p => p.WarrantyPackageCode == code);
                }
                if (!string.IsNullOrWhiteSpace(name))
                {
                    resutl = resutl.Where(p => p.WarrantyPackageName.Contains(name));
                }
                if (period != null)
                {
                    resutl = resutl.Where(p => p.WarrantyPeriod == period && p.PeriodType == unit);
                }
                if (disabled != null)
                {
                    resutl = resutl.Where(p => p.Disabled == disabled);
                }
                totalRecord = resutl.Count();
                return resutl.Skip(((currentPage - 1) < 0 ? 0 : (currentPage - 1)) * pageSize).Take(pageSize).ToList();
            }
        }

        public static pa_WarrantyPackage GetOne(string packageCode)
        {
            using (var context = new DBWarrantyDataContext(AppSetting.ConnectionString))
            {
                return context.pa_WarrantyPackages.FirstOrDefault(p => p.WarrantyPackageCode == packageCode);
            }
        }

        public static List<pa_WarrantyPackage> GetAll()
        {
            using (var context = new DBWarrantyDataContext(AppSetting.ConnectionString))
            {
                return context.pa_WarrantyPackages.ToList();
            }
        }

        public static bool CheckExists(string packageCode)
        {
            using (var context = new DBWarrantyDataContext(AppSetting.ConnectionString))
            {
                return context.pa_WarrantyPackages.Any(p => p.WarrantyPackageCode == packageCode);
            }
        }
    }
}
